<template>
  <div>
    <div class="hello">
      <el-row class="table-grid-content">
        <el-col :span="18" class="grid">
          <el-input v-model="input" placeholder="请输入搜索内容"></el-input>
        </el-col>
        <el-col :span="3" class="grid" :gutter="1">
          <el-button type="success" icon="el-icon-search">搜索</el-button>
        </el-col>
        <el-col :span="2" class="grid" :gutter="15">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <el-col :span="12">
          <el-button size="mini" @click="dels">批量删除</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table :data="tables" style="width: 100%">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="日期" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.createdTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="姓名" width="180">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>姓名: {{ scope.row.username }}</p>
            <p>密码: {{ scope.row.password }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.username }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
  <el-form :model="form">
    <el-form-item label="用户名：" :label-width="formLabelWidth">
      <el-input v-model="form.username" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="密码：" :label-width="formLabelWidth">
      <el-input v-model="form.password" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogFormVisible = false  ;handleAdd()">确 定</el-button>
  </div>
</el-dialog> -->

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <div class="block">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageIndexChange"
        :current-page="pager.pageIndex"
        :page-size="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.rowsTotal"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  deleteUserById,
  getUserList,
  putUserById,
  addUser,
  getById,
} from "../api/users";
export default {
  data() {
    return {
      tableData: [],
      pager: {
        pageIndex: 1,
        pageSize: 10,
        rowsTotal: 1,
      },
      // delVisible:false,//删除提示弹框的状态
      // msg:"",//记录每一条的信息，便于取id
      // delarr:[],//存放删除的数据
      // multipleSelection:[],//多选的数据
      multipleSelection: [],

      input: "",

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      form: {},
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
      },
      formLabelWidth: "120px",
    };
  },

  //搜索
  computed: {
    tables() {
      const input = this.input;
      if (input) {
        console.log("input输入的搜索内容：" + this.input);
        return this.tableData.filter((data) => {
          console.log("object:" + Object.keys(data));
          return Object.keys(data).some((key) => {
            return String(data[key]).toLowerCase().indexOf(input) > -1;
          });
        });
      }
    
      return this.tableData;
    },
  },

  mounted() {
    this.fetchData(this.pager);
  },

  methods: {
    //       批量删除行
    //      @param {object} row 行数据
    //      @param {number} i 数据的序号

    dels(row, i) {
      if (row) {
        if (!row.id) {
          this.tableData.splice(i, 1);
          return false;
        }

        this.tableData
          .dels({ id: row.id })
          .then((res) => {
            if (res.status === 200) {
              this.$message.success("删除成功");
              this.getList();
            } else {
              this.$message.error("获取数据失败");
            }
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      } else {
        if (this.multipleSelection.length === 0) {
          this.$message.warning("请至少选择一行数据");
          return false;
        }
        const id = this.multipleSelection
          .filter((item) => item.id)
          .map((item) => item.id)
          .join(",");
        this.tableData
          .dels({ id })
          .then((res) => {
            if (res.status === 200) {
              this.$message.success("删除成功");
              this.getList();
            } else {
              this.$message.error("获取数据失败");
            }
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      }
    },

    //编辑
    handleEdit(index, row) {
      //  this.reset();
      // var id = row.id || this.tableData
      // console.log(id);
      // console.log(row);
      // putUserById(id).then(({data}) => {

      //   this.form = data.data.data;
      //   this.open = true;
      //   this.title = "修改用户";
      // });
      this.reset();
      //获取数据库相应id
      const id = row.id || this.tableData;
      //相应把数据库id在点编辑时存入到form对象里
      this.form.id = row.id;
      // console.log(id);

      // putUserById(id,{username:row.username,password:row.password}).then(response => {
      //   this.form = response.data.data;
      //   this.open = true;
      //   this.title = "修改用户";
      // });
      //根据查找出的对象进行修改
      getById(id).then((response) => {
        this.form.username = response.data.username;
        this.form.password = response.data.password;
        this.open = true;
        this.title = "修改用户";
      });
    },

    //表单重置
    reset() {
      this.form = {
        id: null,
        username: null,
        password: null,
        createTime: null,
      };
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    //提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        //判断是添加还是修改按钮
        if (valid) {
          //判断是否有用户名和密码
          if (this.form.id !== null) {
            // console.log(this.form.id);
            // console.log(this.form.username);
            //根据点编辑时存入的id做出修改并且把数据传回后端
            putUserById(this.form.id, {
              username: this.form.username,
              password: this.form.password,
            }).then((response) => {
              console.log(response);
              //提示信息
              this.$message({
                showClose: true,
                message: "修改成功",
                type: "success",
              });
              this.open = false;
              //更新首页数据
              this.fetchData(this.pager);
            });
          } else {
            //根据在表单里填的数据，传回到后端，并且存入到数据库
            addUser(this.form).then((response) => {
              console.log(response);
              this.$message({
                showClose: true,
                message: "新增成功",
                type: "success",
              });
              this.open = false;
              this.fetchData(this.pager);
            });
          }
        }
      });
    },

    //删除
    handleDelete(index, row) {
      //移除tableData对象里的相应数据，达到前端删除不用刷新页面
      this.tableData.splice(index, 1);
      //根据相应id删除相应数据e
      deleteUserById(row.id);
      //当删除一条数据时页面上相应的总数据也跟着减一
      this.pager.rowsTotal = this.pager.rowsTotal - 1;

      console.log(row);
      console.log(index);
    },

    //添加
    handleAdd() {
      //重置表单
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },

    //分页
    handlePageSizeChange(val) {
      console.log(`每页 ${val} 条`);

      this.pager.pageSize = val;
      this.fetchData(this.pager);
    },
    handlePageIndexChange(val) {
      console.log(`当前页: ${val}`);

      this.pager.pageIndex = val;
      this.fetchData(this.pager);
    },
    fetchData(pager) {
      getUserList(pager).then((data) => {
        console.log(data);
        this.tableData = data.data.data;
        this.pager = data.data.pager;
      });
    },
  },
};
</script>
